import subprocess
from collections import OrderedDict

class OSDetector:
    def __init__(self):
        self.os_entries = []

    def detect_os(self):
        """
        调用 os-prober 检测操作系统
        返回格式: [{'name': 'Ubuntu', 'device': '/dev/sda1', 'type': 'linux', 'boot': '/boot/vmlinuz'}, ...]
        """
        try:
            output = subprocess.check_output(["os-prober"], stderr=subprocess.STDOUT, text=True)
        except (subprocess.CalledProcessError, FileNotFoundError):
            return []

        for line in output.strip().splitlines():
            if not line:
                continue
            device, name, short_name, os_type = line.split(":")
            if "Linux" in name:
                kernel = self._find_kernel(device)
                initrd = self._find_initrd(device)
                self.os_entries.append({
                    "name": name,
                    "device": device,
                    "type": os_type,
                    "kernel": kernel,
                    "initrd": initrd
                })
            elif "Windows" in name or "macOS" in name:
                self.os_entries.append({
                    "name": name,
                    "device": device,
                    "type": os_type
                })

        return self.os_entries

    def _find_kernel(self, device):
        """查找kernel路径"""
        try:
            return subprocess.check_output(
                ["find", f"{device}/boot", "-name", "vmlinuz-*"],
                stderr=subprocess.DEVNULL,
                text=True
            ).strip().splitlines()[0]
        except:
            return "/boot/vmlinuz"

    def _find_initrd(self, device):
        """查找initrd路径"""
        try:
            return subprocess.check_output(
                ["find", f"{device}/boot", "-name", "initrd.img-*"],
                stderr=subprocess.DEVNULL,
                text=True
            ).strip().splitlines()[0]
        except:
            return "/boot/initrd.img"